/*
 * @Author:php
 * @Date: 2019-7-11 14:11:07
 * @Last Modified by: puhuaping
 * @Last Modified time: 
 * @describe多供应商管理
 */

<template>
  <div>
    <Card>
      <Row>
        <Col span="20">
          <Form inline :label-width="80">
            <FormItem label="供应商ID">
              <Input v-model="formSearch.id" placeholder="请输入供应商ID"></Input>
            </FormItem>
            <FormItem label="供应商名称">
              <Input v-model="formSearch.name" placeholder="请输入供应商名称"></Input>
            </FormItem>
            <FormItem label="联系方式">
              <Input v-model="formSearch.mobile" placeholder="请输入联系方式"></Input>
            </FormItem>
          </Form>
        </Col>
        <Col class="btnBox" span="4">
          <Button
            type="primary"
            :style="{marginLeft:'5px',marginBottom:'5px'}"
            @click="handleSubmit"
          >查询</Button>
          <Button
            type="success"
            :style="{marginLeft:'5px' ,marginBottom:'5px'}"
            @click="checkAll"
          >查看全部</Button>
        </Col>
      </Row>

      <div class="operate-btn-wrap">
        <Button type="primary" @click="addPublicNum">新增供应商</Button>
      </div>

      <Table
        :columns="column"
        stripe
        no-data-text="<i class='ivu-icon ivu-icon-ios-battery-dead'><p class='noData'>无数据</p>"
        :data="tableData"
      ></Table>
      <div class="table-footer">
        <Page
          :current="page.current_page"
          :total="page.total"
          :page-size="page.per_page"
          show-total
          show-elevator
          @on-change="handleChange"
        />
      </div>
      <Modal :title="isAdd?'新增供应商':'编辑供应商'" :mask-closable='false' v-model="visible" width="450" @on-cancel="clearModule">
        <Form :model="formData" :rules="ruleValidate" inline :label-width="100" ref="wechatForm">
          <FormItem label="供应商名称" prop="name">
            <Input
              :disabled="!isAdd"
              v-model="formData.name"
              placeholder="请输入供应商名称"
              style="width:280px;"
            />
          </FormItem>
          <FormItem label="联系人" prop="contact">
            <Input v-model="formData.contact" placeholder="请输入供应商联系人姓名" style="width:280px;" />
          </FormItem>
          <FormItem label="联系方式" prop="mobile">
            <Input v-model="formData.mobile" placeholder="请输入供应商联系人联系方式" style="width:280px;" />
          </FormItem>
          <FormItem label>
            <p>该联系方式将作为供应商唯一登录凭证，请谨慎填写。</p>
          </FormItem>
          <!-- <FormItem label="结算主体" prop="settnames">
            <Input
              :disabled="!isAdd"
              v-model="formData.settnames"
              placeholder="请输入结算主体"
              style="width:280px;"
            />
          </FormItem> -->
          <FormItem label="结算性质">
            <RadioGroup v-model="formData.type" @on-change="changeType">
              <Radio label="对公" :disabled="!isAdd">对公</Radio>
              <Radio label="对私" :disabled="!isAdd">对私</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem :label="formData.type=='对公'?'公司名称':'姓名'" prop="bankaddress">
            <Input
              :disabled="!isAdd"
              v-model="formData.bankaddress"
              :placeholder="formData.type=='对公'?'请输入对公企业全称':'请输入对私负责人姓名'"
              style="width:280px;"
            />
          </FormItem>
          <FormItem label="开户行" prop="cardnumber">
            <Input
              :disabled="!isAdd"
              v-model="formData.cardnumber"
              :placeholder="formData.type=='对公'?'请输入企业公账开户行':'请输入对私负责人姓名'"
              style="width:280px;"
            />
          </FormItem>
          <FormItem label="账号" prop="username">
            <Input
              :disabled="!isAdd"
              v-model="formData.username"
              :placeholder="formData.type=='对公'?'请输入企业对公银行账号':'请输入对私银行账户开户行'"
              style="width:280px;"
            />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button style="margin-right: 8px" @click="clearModule">取消</Button>
          <Button type="primary" @click="sureWechat">确认</Button>
        </div>
      </Modal>
    </Card>
  </div>
</template>
<script>
import InforCard from "_c/info-card";
import CountTo from "_c/count-to";
import { getData, getList } from "@/api/data";
import { getToken } from "@/libs/util";
import config from "@/config";
const baseUrl =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.dev
    : config.baseUrl.pro;
export default {
  name: "publicNumManageIndex",
  components: {
    InforCard,
    CountTo
  },
  data() {
    return {
      formDataOrigin: {
        id: "",
        name: "",
        type: "对公",
        contact: "",
        mobile: "",
        bankaddress: "",
        cardnumber: "",
        // settnames: "",
        username: ""
      },
      formData: {
        id: "",
        type: "对公",
        name: "",
        contact: "",
        mobile: "",
        bankaddress: "",
        // settnames: "",
        cardnumber: "",
        username: ""
      },
      ruleValidate: {
        name: [{ required: true, message: "请输入供应商名称" }],
        contact: [{ required: true, message: "请输入供应商联系人姓名" }],
        mobile: [
          {
            required: true,
            pattern: /^1[23456789]\d{9}$/,
            message: "请输入正确供应商联系人联系方式"
          }
        ],
        settnames: [{ required: true, message: "请输入结算主体" }],
        bankaddress: [{ required: true, message: "请输入" }],
        cardnumber: [{ required: true, message: "请输入" }],
        username: [{ required: true, message: "请输入" }]
      },
      visible: false,
      isAdd: true,
      formSearch: {
        name: "",
        mobile: "",
        id: ""
      },
      dataArea: [], //级联区域
      column: [
        {
          title: "供应商ID",
          align: "center",
          key: "id",
          minWidth: 100
        },
        {
          title: "供应商名称",
          align: "center",
          minWidth: 160,
          key: "name"
        },
        {
          title: "联系人",
          align: "center",
          key: "contact",
          minWidth: 160
        },
        {
          title: "联系方式",
          align: "center",
          key: "mobile",
          minWidth: 160
        },
        {
          title: "结算性质",
          align: "center",
          key: "type",
          minWidth: 160
        },
        {
          title: "结算主体",
          align: "center",
          key: "settnames",
          minWidth: 160
        },
        {
          title: "开户行",
          align: "center",
          key: "cardnumber",
          minWidth: 160
        },
        {
          title: "银行卡号",
          align: "center",
          key: "username",
          minWidth: 160
        },
        {
          title: "账户余额",
          align: "center",
          key: "balance",
          minWidth: 160
        },
        {
          title: "状态",
          minWidth: 100,
          align: "center",
          render: (h, params) => {
            return h("span", {}, params.row.status == "0" ? "启用" : "禁用");
          }
        },
        {
          title: "登录次数",
          align: "center",
          key: "logintimes",
          minWidth: 160
        },
        {
          title: "最近登录时间",
          align: "center",
          key: "lasttime",
          minWidth: 160
        },
        {
          title: " ",
          align: "center",
          key: ""
        },
        {
          title: "操作",
          align: "center",
          width: 240,
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  on: {
                    click: () => {
                      let text = params.row.status == "0" ? "禁用" : "启用";
                      let status = params.row.status == "0" ? "1" : "0";
                      this.$Modal.confirm({
                        title: "提示",
                        width: "300px",
                        content: `是否确定要${text}该供应商？`,
                        onOk: () => {
                          getData(`/supplier.supplier/setStatus`, {
                            id: params.row.id,
                            status
                          }).then(res => {
                            if (res.data.code == 0) {
                              this.$Message.success(`${text}成功`);
                              this.getListData();
                            } else {
                              this.$Message.error(res.data.msg);
                            }
                          });
                        }
                      });
                    }
                  },
                  attrs: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  }
                },
                params.row.status == "0" ? "禁用" : "启用"
              ),
              h(
                "Button",
                {
                  on: {
                    click: () => {
                      this.$refs.wechatForm.resetFields();
                      this.visible = true;
                      this.isAdd = false;
                      let {
                        name,
                        type,
                        contact,
                        username,
                        mobile,
                        bankaddress,
                        cardnumber,
                        // settnames,
                        id
                      } = params.row;
                      this.formData = {
                        id: id,
                        name,
                        type,
                        contact,
                        mobile,
                        bankaddress,
                        cardnumber,
                        // settnames,
                        username
                      };
                    }
                  },
                  style: {
                    marginRight: "5px"
                  },
                  attrs: {
                    type: "primary",
                    size: "small"
                  }
                },
                "编辑"
              ),
              // h(
              //   "Button",
              //   {
              //     on: {
              //       click: () => {
              //         this.$Modal.confirm({
              //           title: "提示",
              //           width: "300px",
              //           content: "是否确定要删除该供应商？",
              //           onOk: () => {
              //             getData(`/wechat.show/del`, {
              //               id: params.row.id
              //             }).then(res => {
              //               if (res.data.code == 0) {
              //                 this.$Message.success("删除成功");
              //                 this.getListData();
              //               } else {
              //                 this.$Message.error(res.data.msg);
              //               }
              //             });
              //           }
              //         });
              //       }
              //     },
              //     style: {
              //       marginRight: "5px"
              //     },
              //     attrs: {
              //       type: "error",
              //       size: "small"
              //     }
              //   },
              //   "删除"
              // ),
              h(
                "Button",
                {
                  on: {
                    click: () => {
                      getData("/supplier.Supplier/login", {
                        suppid: params.row.id
                      }).then(res => {
                        if (res.data.code == 0) {
                          window.open(res.data.data.url);
                          // window.open(
                          //   "http://localhost:8080/login?token=" +
                          //     res.data.data.logintoken
                          // );
                        }
                      });
                      // window.open(
                      //   `${baseUrl}/supers/wechat.show/login?id=${
                      //     params.row.id
                      //   }&token=${getToken()}`
                      // );
                    }
                  },
                  attrs: {
                    type: "primary",
                    size: "small"
                  }
                },
                "越权登录"
              )
            ]);
            return;
          }
        }
      ],
      tableData: [],
      page: {
        current_page: 1,
        total: 0,
        per_page: 10
      }
    };
  },
  created() {
    this.getListData();
  },
  methods: {
    //改变结算性质
    changeType() {
      this.$refs.wechatForm.fields.forEach(e => {
        if (
          e.prop == "bankaddress" ||
          e.prop == "cardnumber" ||
          e.prop == "username"
        ) {
          e.resetField();
        }
      });
    },
    //关闭弹窗
    clearModule() {
      this.visible = false;
      this.isAdd = true;
      this.formData = {
        ...this.formData,
        ...this.formDataOrigin
      };
      this.$refs.wechatForm.resetFields();
    },
    //提交form
    sureWechat() {
      if (this.isAdd) {
        this.$refs["wechatForm"].validate(valid => {
          if (valid) {
            this.requestSupplier("/supplier.Supplier/add", "新增成功");
          }
        });
      } else {
        let fieldsToValidate = ["contact", "mobile"];
        let _self = this;
        Promise.all(
          fieldsToValidate.map(item => {
            let p = new Promise(function(resolve, reject) {
              _self.$refs["wechatForm"].validateField(item, error => {
                resolve(error);
              });
            });
            return p;
          })
        ).then(data => {
          let mark = data.every(item => {
            return !item;
          });
          if (mark) {
            _self.requestSupplier("/supplier.supplier/edit", "编辑成功");
          }
        });
      }
    },
    requestSupplier(url, text) {
      let params = { ...this.formData };
      for (let i in params) {
        if (params[i] === "") {
          delete params[i];
        }
      }
      getData(url, params).then(res => {
        if (res.data.code == 0) {
          this.visible = false;
          this.$Message.success(text);
          this.visible = false;
          this.isAdd = true;
          this.formData = {
            ...this.formData,
            ...this.formDataOrigin
          };
          this.getListData();
        }
      });
    },
    //新增供应商
    addPublicNum() {
      this.visible = true;
    },
    //查看全部
    checkAll() {
      this.page.current_page = 1;
      this.formSearch = {
        name: "",
        mobile: "",
        id: ""
      };
      this.getListData();
    },
    //查询
    handleSubmit() {
      this.page.current_page = 1;
      this.getListData();
    },
    //获取分页
    handleChange(e) {
      this.page.current_page = e;
      this.getListData();
    },
    getListData() {
      const params = Object.assign(
        {
          page: this.page.current_page,
          limit: this.page.per_page
        },
        this.formSearch
      );
      getData(`/supplier.Show/list`, params).then(res => {
        if (res.data.code === 0) {
          this.tableData = res.data.data.data;
          const { current_page, total, per_page } = res.data.data;
          this.page = {
            current_page: current_page ? Number(current_page) : 0,
            total: total ? total : 0,
            per_page: per_page ? Number(per_page) : 0
          };
        }
      });
    }
  },

  mounted() {}
};
</script>
<style lang="less">
.btnBox {
  text-align: right;
}
.operate-btn-wrap {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}
.table-footer {
  display: flex;
  justify-content: flex-end !important;
  margin-top: 20px;
  .tiptext {
    color: rgb(92, 146, 232);
    font-size: 12px;
    span {
      display: inline-block;
      margin-right: 10px;
    }
  }
}
.noData {
  font-size: 12px;
  padding-bottom: 24px;
}
.ivu-icon-ios-battery-dead {
  font-size: 55px;
  color: #5c92e8;
}
</style>
